from typing import Any

from internal.exception import FailException
from pkg.sqlalchemy import SQLAlchemy


class BaseService:
    db: SQLAlchemy

    def create(self, model: Any, **kwargs):
        with self.db.auto_commit():
            model_data = model(**kwargs)
            self.db.session.add(model_data)
            return model_data

    def update(self, model: Any, **kwargs):
        with self.db.auto_commit():
            for k, v in kwargs.items():
                if hasattr(model, k):
                    setattr(model, k, v)
                else:
                    raise FailException("更新数据失败")
            return model

    def delete(self, model: Any):
        with self.db.auto_commit():
            self.db.session.delete(model)
        return model

    def get(self, model: Any, primary_key: Any):
        data = self.db.session.query(model).get(primary_key)
        return data
